/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedFaceData, pickedLineData, pickedVertexData } from '@amcax/base';
import {
  NumberInputFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { omitBy } from 'lodash';
import { useMemo, useState } from 'react';

import { CurvedBaseCommand, CurvedCmdDialogParams } from '@app-cad/types';

type OffsetMode = 'byDistance' | 'rabyPointtio';

type FormData = {
  curve?: pickedLineData;
  surface?: pickedFaceData;
  offsetmode: string;
  distance?: number;
  bothdir?: boolean;
  reverse?: boolean;
  point?: pickedVertexData;
};

type Params = {
  curve: string;
  surface: string;
  offsetmode: OffsetMode;
  distance?: number;
  bothDir?: boolean;
  isReverse?: boolean;
  point?: string;
};

// 平行曲线
// FIXME: 目前nextcore不支持法则曲线，所以这里没加上
function ParallelCurve({ title, onClose, props }: CurvedCmdDialogParams) {
  const initData: FormData = {
    offsetmode: 'byDistance',
    bothdir: false,
    reverse: false,
  };

  const [formData, setFormData] = useState<FormData>(initData);

  const { picker } = useTools();

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData(initData);
      return;
    }

    const { curve, surface, offsetmode, distance, bothDir, isReverse, point } =
      props.params as Params;

    await initEditDependency([curve, surface, point]);

    const curveObj = picker.generatePickObjByPickID(curve) as pickedLineData;
    const surfaceObj = surface
      ? (picker.generatePickObjByPickID(surface) as pickedFaceData)
      : null;
    const pointObj = point
      ? (picker.generatePickObjByPickID(point) as pickedVertexData)
      : null;

    setFormData({
      curve: curveObj,
      surface: surfaceObj,
      offsetmode: offsetmode,
      distance: distance == null ? 0.0 : distance,
      bothdir: bothDir == null ? false : bothDir,
      reverse: isReverse == null ? false : isReverse,
      point: pointObj,
    });
  }, []);

  const isFormDataValid = () => {
    const { curve, offsetmode, point } = formData;

    if (curve == null) {
      return false;
    }

    if (offsetmode === 'rabyPointtio') {
      if (point == null) {
        return false;
      }
    }

    return true;
  };

  useAsyncEffect(async () => {
    if (!isFormDataValid()) {
      clear();
      return;
    }

    await execute(true);
  }, [formData]);

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    await execute(false);

    onClose();
  };

  const { initEditDependency, initingEdit, clear, confirmCommand, isLoading } =
    useCommand('cmd-curve-parallel', {
      commandName: 'CreateCurve',
      editDxid: props?.shape,
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const execute = (preview: boolean) => {
    const { curve, surface, offsetmode, distance, bothdir, reverse, point } =
      formData;

    return confirmCommand(
      {
        type: 'Parallel',
        a: {
          curve: curve.edgeId,
          surface: surface?.meshId,
          offsetmode: offsetmode,
          distance: distance == null ? 0.0 : distance,
          bothDir: bothdir,
          isReverse: reverse,
          point: point?.vertexId,
        },
      },
      preview,
    );
  };

  const schema: RJSFSchema = useMemo(() => {
    const properties = omitBy(
      {
        point:
          formData.offsetmode === 'rabyPointtio'
            ? {
                type: 'string',
                format: PickInputRJSFFormat.PickVertex,
              }
            : null,
        distance:
          formData.offsetmode === 'byDistance'
            ? {
                type: 'number',
                title: '距离',
                default: 0,
                format: NumberInputFormat.Length,
              }
            : null,
        reverse:
          formData.offsetmode === 'byDistance'
            ? {
                type: 'boolean',
                title: '反转方向',
              }
            : null,
        bothdir:
          formData.offsetmode === 'byDistance'
            ? {
                type: 'boolean',
                title: '双侧',
              }
            : null,
      },
      (val) => val == null,
    );

    return {
      type: 'object',
      properties: {
        curve: {
          title: '曲线',
          type: 'string',
          format: PickInputRJSFFormat.PickCurve,
        },
        surface: {
          title: '支持面',
          type: 'string',
          format: PickInputRJSFFormat.PickSurface,
        },
        offsetmode: {
          title: '偏移',
          type: 'string',
          oneOf: [
            {
              type: 'string',
              title: '通过点',
              const: 'rabyPointtio',
            },
            {
              type: 'number',
              title: '距离',
              const: 'byDistance',
            },
          ],
          default: 'byDistance',
        },
        ...properties,
      },
    } as RJSFSchema;
  }, [formData.offsetmode]);

  return (
    <PickableCommandForm
      disabled={initingEdit}
      onClose={onClose}
      submitLoading={isLoading}
      title={title}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        setFormData(v);
      }}
      extraUiSchema={{
        curve: {
          'ui:placeholder': '请输入曲线',
          'ui:autofocus': true,
          'ui:options': {
            showArrow: true,
            curveReversable: true,
          },
        },
        surface: {
          'ui:placeholder': '请选择支持面',
          'ui:options': { allowInfinitePlane: true },
        },
        point: {
          'ui:placeholder': '请输入点',
        },
        distance: {
          'ui:placeholder': '请输入距离',
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
}

export const cmdCurveParallel: CurvedBaseCommand = {
  id: 'CommandCurveParallel',
  label: 'command.curve.parallel-curve',
  icon: 'commands/curved/parallel-curve',
  create: (label, onClose, props) => (
    <ParallelCurve
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
